<?php

namespace app\api\controller\v1;

use app\api\model\v1\Dianpu;
use app\api\model\wanlshop\Brand;
use app\api\model\wanlshop\Category;
use app\api\model\wanlshop\Shop as WanlshopShop;
use app\common\controller\Api;
use app\common\controller\Shopapi;
use app\common\model\Config;
use app\index\model\wanlshop\Goods;
use fast\Random;
use think\Db;
use think\Exception;
use think\exception\PDOException;
use think\exception\ValidateException;

/**
 * 商家接口
 */
class Shop extends Shopapi
{
    protected $noNeedLogin =['login'] ;
    protected $noNeedRight = ['*'];

   

  
     
	 //商家 or 塘主  App登录
	 public function  login(){
		$mobile = $this->request->post('mobile');
		$password = $this->request->post('password');
		if (!$mobile || !$password) {
			$this->error(__('Invalid parameters'));
		}

		$ret = $this->shopauth->login($mobile, $password);
		if ($ret) {
			$this->success(__('Logged in successful'), WanlshopShop::get(['mobile'=>$mobile]));
		} else {
			$this->error($this->shopauth->getError());
		}
		
	 }
	 

	 //新建店铺 
	 public function  add_dianpu(){
		$shop = $this->shopauth->getUser();

		// //设置过滤方法
		$this->request->filter(['strip_tags']);
		
		
		//查询最近的提交
		$row_zuijin = Dianpu::where(['shop_id' => $shop->id])->order('createtime desc')
			->find();


		if ($this->request->isPost()) {
			$params = $this->request->post();
			//先判断是否是待审核的店铺
			$row_daishenhe = Dianpu::where(['shop_id' => $shop->id])->where('verify',0)->find();
			if($row_daishenhe){
				$this->error('有待审核的店铺,无法新建新的店铺');
			}
			
			$is_name =  Dianpu::where(['dianpu_name' => $params['dianpu_name']])->find();
			if($is_name){
				$this->error('店铺名称已经被使用了，请更换');
			}
			$params['shop_id'] = $shop->id;
			// if($row){
			// 	$row->save($params);
			// }else{
				Dianpu::create($params);
			// }
			$this->success('返回成功', $params);
		}
		$this->success('返回成功', $row_zuijin);

	 }

	 //我的店铺列表
	 public function my_dianpu(){
		$shop = $this->shopauth->getUser();
		
		$list = Dianpu::where('shop_id',$shop->id)->where('verify',1)->select();
		if(!$list){
			$this->error('无店铺,请去新建','',11);
		}
		$this->success('成功',$list);

	 }

	 //店铺资质
	 public function dianpu_detail(){
		$id = $this->request->post('dianpu_id');
		
		$detail = Dianpu::where('id',$id)->where('verify',1)->find();
		if(!$detail){
			$this->error('无店铺');
		}
		$this->success('成功',$detail);
	 }

	//  //新增/编辑商品
	//  public function  add_eit_goods(){

	//  }

	//分类列表
	public function catelist(){
		$catelist  = Category::where('status','normal')->field('id,name')->order('weigh desc')->select();
		$this->success('成功',$catelist);
	}

	//品牌列表
	public function brandlist(){
		$Brandlist  = Brand::where('status','normal')->field('id,name')->order('weigh desc')->select();
		$this->success('成功',$Brandlist);
	}

	    /**
     * 添加
     */
	public function add()
	{

		$shop = $this->shopauth->getUser();
		//设置过滤方法
		$this->request->filter(['']);
	    if ($this->request->isPost()) {
	        $params = $this->request->post();
	        if ($params) {
				// 判断产品属性是否存在
				empty($params['spuItem'])?$params['specs'] = 'single':$params['specs'] = 'multi';
	          
	            Db::startTrans();
	            try {
					if($params['specs'] == 'single'){ //无多规格
						$goods = new Goods;
						// 获取自增ID
						$goods->shop_id     = $shop->id;
						$goods->brand_id    = $params['brand_id'];
						$goods->title       =    $params['title'];
						$goods->category_id = $params['category_id'];
						$goods->dianpu_id   = $params['dianpu_id'];
						$goods->price = $params['price'];
						$goods->vip_price = $params['vip_price'];
						$goods->image = $params['image'];
						$goods->images = $params['images'];
						$goods->description = $params['description'];
						$goods->stock = $params['stock'];

						$goods->content = $params['content'];
						$goods->is_score = $params['is_score'];
						$goods->score = $params['score'];
						$goods->exchange_days = $params['exchange_days']?$params['exchange_days'] : 1;
						$goods->sn = rand(1000000, 9999999);
						$goods->save();
					
					}else{
						$spudata = isset($params['spu'])?$params['spu']:$this->error(__('请填写产品属性'));
						$spuItem = isset($params['spuItem'])?$params['spuItem']:$this->error(__('请填写产品属性-产品规格'));
						$goods = new Goods;
						// 获取自增ID
						$goods->shop_id     =$shop->id;
						$goods->brand_id    = $params['brand_id'];
						$goods->title       =    $params['title'];
						$goods->category_id = $params['category_id'];
						$goods->dianpu_id   = $params['dianpu_id'];
						$goods->price = $params['price'];
						$goods->vip_price = $params['vip_price'];
						$goods->image = $params['image'];
						$goods->images = $params['images'];
						$goods->description = $params['description'];
						$goods->stock = $params['stock'];

						$goods->content = $params['content'];
						$goods->is_score = $params['is_score'];
						$goods->score = $params['score'];
						$goods->exchange_days = $params['exchange_days']?$params['exchange_days'] : 1;
						$goods->sn = rand(1000000, 9999999);

					
						// $this->model->price = min($params['price']);
						$goods->save();
						
					
	            
						$result = true;
						// 写入SPU
						$spu = [];
						foreach (explode(",", $spudata) as $key => $value) {
							$spu[] = [
								'goods_id'	=> $goods->id,
								'name'		=> $value,
								'item'		=> $spuItem[$key]
							];
						}
						if(!model('app\index\model\wanlshop\GoodsSpu')->allowField(true)->saveAll($spu)){
							$result == false;
						}
						// 写入SKU
						$sku = [];
						foreach ($params['sku']  as $key => $value) {
							$sku[] = [
								'goods_id' 		=> $goods->id,
								'thumbnail' 	=> isset($params['thumbnail']) ? $params['thumbnail'][$key] : false, // 1.0.8升级
								'difference' 	=> $value,
								'vip_price' 	=> $params['vip_prices'][$key],
								'score' 	    => $params['scores'][$key],
								'flash_price' 	=> $params['flash_prices'][$key],
								'price' 		=> $params['prices'][$key],
								'stock' 		=> $params['stocks'][$key],
								// 'weigh' 		=> $params['weigh'][$key]!=''?$params['weigh'][$key] : 0,
								// 'sn' 			=> $params['sn'][$key]!=''?$params['sn'][$key] : 'wanl_'.time()
							];
						}
						if(!model('app\index\model\wanlshop\GoodsSku')->allowField(true)->saveAll($sku)){
							$result == false;
						}

						if ($result !== false) {
							$this->success();
						} 



					}
	                
	                Db::commit();
	            } catch (ValidateException $e) {
	                Db::rollback();
	                $this->error($e->getMessage());
	            } catch (PDOException $e) {
	                Db::rollback();
	                $this->error($e->getMessage());
	            } catch (Exception $e) {
	                Db::rollback();
	                $this->error($e->getMessage());
	            }
	            
	        }
	    
	    }
	   
		$this->success('添加成功');
	}
    
    /**
     * 编辑
     */
    public function edit()
    {
		//设置过滤方法
		$params = $this->request->post();
		$goods = new Goods;
		
        $goods = $goods->get($params['id']);
        if (!$goods) {
            $this->error(__('No Results were found'));
        }
		
       
		// 查询SKU
		$skuItem = model('app\index\model\wanlshop\GoodsSku')
			->where(['goods_id' => $params['id'], 'state' => 0])
			->select();
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
				// 判断产品属性是否存在
				empty($params['spuItem'])?$params['specs'] = 'single':$params['specs'] = 'multi';
                $result = false;
                Db::startTrans();
                try {

					if($params['specs'] == 'single'){ //无多规格

				
						// 写入表单
						$data = $params;
						if(isset($data['attribute'])){
							$data['category_attribute'] = json_encode($data['attribute'], JSON_UNESCAPED_UNICODE);
						}

						$result = $goods->allowField(true)->save($data);
						// 删除原来数据,重新写入SPU
						model('app\index\model\wanlshop\GoodsSpu')
							->where('goods_id',$params['id'])
							->delete();

						//标记旧版SKU数据
						model('app\index\model\wanlshop\GoodsSku')
							->where('goods_id',$params['id'])
							->update(['state' => 1]);
						

					}else{ //有规格

						$spudata = isset($params['spu'])?$params['spu']:$this->error(__('请填写销售信息-产品属性'));
						$spuItem = isset($params['spuItem'])?$params['spuItem']:$this->error(__('请填写销售信息-产品属性-产品规格'));
						// 写入表单
						$data = $params;
						
						// $data['price'] = min($data['price']);
						$result = $goods->allowField(true)->save($data);
						// 删除原来数据,重新写入SPU
						model('app\index\model\wanlshop\GoodsSpu')
							->where('goods_id',$params['id'])
							->delete();
						$spu = [];
						foreach (explode(",", $spudata) as $key => $value) {
							$spu[] = [
								'goods_id' => $params['id'],
								'name' => $value,
								'item' => $spuItem[$key]
							];
						}
						if(!model('app\index\model\wanlshop\GoodsSpu')->allowField(true)->saveAll($spu)){
							$result == false;
						}
						//标记旧版SKU数据
						$oldsku = [];
						foreach ($skuItem as $value) {
							$oldsku[] = [
								'id' => $value['id'],
								'state' => 1
							];
						}
						if(!model('app\index\model\wanlshop\GoodsSku')->allowField(true)->saveAll($oldsku)){
							$result == false;
						}


						// 写入SKU
						$sku = [];
						foreach ($params['sku'] as $key => $value) {
							$sku[] = [
								'goods_id'     => $goods->id,
								'thumbnail'    => isset($params['thumbnail']) ? $params['thumbnail'][$key] : false, // 1.0.8升级
								'difference'   => $value,
								'vip_price'    => $params['vip_prices'][$key],
								'score' 	   => $params['scores'][$key],
								'flash_price'  => $params['flash_prices'][$key],
								'price' => $params['price'][$key],
								'stock' => $params['stocks'][$key],
							];
						}
						if(!model('app\index\model\wanlshop\GoodsSku')->allowField(true)->saveAll($sku)){
							$result == false;
						}
						if ($result !== false) {
							$this->success();
						} else {
							$this->error(__('No rows were updated'));
						}
						
					}
					
                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
              
            }
            // $this->error(__('Parameter %s can not be empty', ''));
			$this->success('修改成功');
        }

		$spuData = model('app\index\model\wanlshop\GoodsSpu')->all(['goods_id' => $params['id']]);
		if($skuItem){
			$suk = [];
			foreach ($skuItem as $vo) {
				$suk[] = explode(",", $vo['difference']);
			}
			$spu = [];
			foreach ($spuData as $vo) {
				$spu[] = $vo['name'];
			}
			$spuItem = [];
			foreach ($spuData as $vo) {
				$spuItem[] = explode(",", $vo['item']);
			}
			$skulist = [];
			foreach ($skuItem as $vo) {
				$skulist[$vo['difference']] = $vo;
			}

			$goods->spu = $spu;
			$goods->spuItem = $spuItem;
			$goods->sku = $suk;
			$goods->skuItem = $skulist;
	

		}else{
			$goods->spuItem = [];
		}
		$this->success('返回成功',$goods);
	
    }

	// //商品属性
	// public function goods_sku(){
	// 	$params = $this->request->post();
	// 	$goods = new Goods;
		
    //     $goods = $goods->get($params['id']);
    //     if (!$goods) {
    //         $this->error(__('No Results were found'));
    //     }
		
       
	// 	// 查询SKU
	// 	$skuItem = model('app\index\model\wanlshop\GoodsSku')
	// 		->where(['goods_id' => $params['id'], 'state' => 0])
	// 		->select();



	// 	$spuData = model('app\index\model\wanlshop\GoodsSpu')->all(['goods_id' => $params['id']]);

	// 	if($skuItem){
	// 		$suk = [];
	// 		foreach ($skuItem as $vo) {
	// 			$suk[] = explode(",", $vo['difference']);
	// 		}
	// 		$spu = [];
	// 		foreach ($spuData as $vo) {
	// 			$spu[] = $vo['name'];
	// 		}
	// 		$spuItem = [];
	// 		foreach ($spuData as $vo) {
	// 			$spuItem[] = explode(",", $vo['item']);
	// 		}
	// 		$skulist = [];
	// 		foreach ($skuItem as $vo) {
	// 			$skulist[$vo['difference']] = $vo;
	// 		}

	
	// 		$goods->spu = $spu;
	// 		$goods->spuItem = $spuItem;
	// 		$goods->sku = $suk;
	// 		$goods->skuItem = $skulist;
	// 	}else{
	// 		$goods->spuItem = [];
	// 	}
	// 	$this->success('返回成功',$goods);
	// }


	//商品列表
	public function goodslist(){
		$pagesize = $this->request->post('pagesize',10);
		$dianpu_id = $this->request->post('dianpu_id');
		$goods = new Goods;
		$goodslist = $goods->where('status','normal')->where('deletetime is null')
		->where('dianpu_id',$dianpu_id)
		->paginate($pagesize)->each(function ($row){
            $row['category_name']  = Category::where('id',$row['category_id'])->value('name');
			$row['brand_name']  = Brand::where('id',$row['brand_id'])->value('name');
            return $row;
        });
		$this->success('成功',$goodslist);
	}

	//删除商品
	public function del(){
		$id = $this->request->post('id');
		// $dianpu_id = $this->request->post('dianpu_id');
		$goods = new Goods;
		$goods->where('id',$id)->update(['deletetime'=>time()]);
		$this->success('删除成功');
	}
	

	//商品损耗登记

	public function goods_loss_add(){
		$parms = $this->request->post();
		$parms['total_price'] = bcmul($parms['price'],$parms['num'], 2); 
		$parms['createtime'] = time();
		Db::name('dianpu_goods_loss')->insert($parms);
		$this->success('添加成功');
	}

	//本店铺已添加得分类商品(登记时候选择商品下拉)
	// public function cate_goods_list(){
	// 	$parms = $this->request->post();
	// 	$list = Goods::where('category_id',$parms['category_id'])
	// 	->where('dianpu_id',$parms['dianpu_id'])
	// 	->where('status','normal')
	// 	->where('deletetime is null')
	// 	->order('weigh desc')
	// 	->field('id,title')
	// 	->select();
		
	// 	$this->success('成功',$list);
	// }

	//本店铺分类下商品(登记时候选择商品下拉)
	public function cate_goods_list(){
		$parms = $this->request->post();
		$list = Goods::where('category_id',$parms['category_id'])
		->where('dianpu_id',$parms['dianpu_id'])
		->where('status','normal')
		->where('deletetime is null')
		->order('weigh desc')
		->field('id,title')
		->select();
		
		$this->success('成功',$list);
	}

	//商品损耗明细
	public function goods_loss_list_log(){
		$pagesize = $this->request->post('pagesize',10);
		$dianpu_id = $this->request->post('dianpu_id');
		
		$losslist = Db::name('dianpu_goods_loss')->where('deletetime is null')
		->where('dianpu_id',$dianpu_id)
		->paginate($pagesize)->each(function ($row){
            $row['category_name']  = Category::where('id',$row['category_id'])->value('name');
			$row['goods_name']  = Goods::where('id',$row['goods_id'])->value('title');
			$row['createtime']  =date('Y-m-d H:i:s',$row['createtime']);
            return $row;
        });
		$this->success('成功',$losslist);
	}

	//商品损耗列表
	public function goods_loss_list(){

		$pagesize = $this->request->post('pagesize',10);
		$dianpu_id = $this->request->post('dianpu_id');
		

		$list = Db::name('dianpu_goods_loss')
                    ->where('deletetime is null') 
					->where('dianpu_id',$dianpu_id) 
                    ->field('sum(num) as nums,category_id')
                    ->group('category_id')
                    ->order('weigh desc')
                    ->paginate($pagesize)->each(function ($row) use($dianpu_id){
						$row['cate_name'] = Category::where('id',$row['category_id'])->value('name');
						//求出商品id
						$good_ids=  Db::name('dianpu_goods_loss')
						->where('deletetime is null') 
				    	->where('dianpu_id',$dianpu_id) 
						->where('category_id',$row['category_id']) 
						->column('goods_id');
						
						//商品分组求和
						$goods_loss =  Db::name('dianpu_goods_loss')
						->where('deletetime is null') 
						->where('dianpu_id',$dianpu_id) 
						->where('category_id',$row['category_id'])
						->where('goods_id','in',$good_ids)
						->field('sum(num) as nums,sum(total_price) as total_prices,goods_id')
						->group('goods_id')
						->select();
					
						foreach($goods_loss as $k=>$v){
							$goods_loss[$k]['goods_title'] = Goods::where('id',$v['goods_id'])->value('title');
						}
						$row['goods_ing'] = $goods_loss;
						return $row;
					});
			$this->success('成功',$list);		
	}

	public function shopuser(){
		$shopuser = $this->shopauth->getUser();
		$this->success('成功',$shopuser);
	}

	
	/**
     * 修改头像/昵称
     *
     * @ApiMethod (POST)
     * @param string $avatar   头像地址
     * @param string $username 用户名
     * @param string $nickname 昵称
     * @param string $bio      个人简介
     */
    public function user_edit()
    {
        $shopuser = $this->shopauth->getUser();
		
        $shopname = $this->request->post('shopname');
        $avatar = $this->request->post('avatar', '', 'trim,strip_tags,htmlspecialchars');
        if ($shopname) {
            $exists = WanlshopShop::where('shopname', $shopname)->where('id', '<>',$shopuser->id)->find();
            if ($exists) {
                $this->error(__('Username already exists'));
            }
            $shopuser->shopname = $shopname;
        }
       
        if($avatar) $shopuser->avatar = $avatar;
        $shopuser->save();
        $this->success('修改成功');
    }

	/**
     * 修改密码
     *
     * @ApiMethod (POST)
     */
    public function password_edit()
    {
        $shopuser = $this->shopauth->getUser();

		$old_password = $this->request->post('old_password');
		$password = $this->request->post('password');

		if ($shopuser->password != $this->getEncryptPassword($old_password, $shopuser->salt)) {
            $this->error('原密码有误');
        }

		$shopuser->salt    =  Random::alnum();
		$shopuser->password = $this->getEncryptPassword($password, $shopuser->salt);
        $shopuser->save();
        $this->success('修改成功,请用新密码登录');
    }

		/**
     * 意见反馈
     *
     * @ApiMethod (POST)
     */
    public function feed()
    {
        $shopuser = $this->shopauth->getUser();
		$parms = $this->request->post();
		$data = [
			'shop_id' => $shopuser->id,
			'shenfen' => $shopuser->state,
			'content' => $parms['content'],
			'images'  => $parms['images'],
			'createtime' => time(),
		];
		Db::name('shop_feed')->insert($data);
        $this->success('反馈成功');
    }


	 /**
     * 获取密码加密后的字符串
     * @param string $password 密码
     * @param string $salt     密码盐
     * @return string
     */
    public function getEncryptPassword($password, $salt = '')
    {
        return md5(md5($password) . $salt);
    }

}